package mall

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzmall"
	"private-domain-overseas-service/tools/ent/predicate"
)

type MallDao struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMallDao(ctx context.Context, svcCtx *svc.ServiceContext) *MallDao {
	return &MallDao{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// MallCreate -添加商城
func (l *MallDao) MallCreate(mall *ent.HzMall, tx *ent.Tx) (*ent.HzMall, error) {
	clientDao := l.svcCtx.Orm.HzMall
	if tx != nil {
		clientDao = tx.HzMall
	}
	hzMall, err := clientDao.Create().SetMallSort(mall.MallSort).
		SetMallIcon(mall.MallIcon).
		SetMallName(mall.MallName).
		SetMallURL(mall.MallURL).
		SetMallStatus(mall.MallStatus).
		SetCreatedAt(mall.CreatedAt).
		SetUpdateAt(mall.UpdateAt).
		Save(l.ctx)
	if err != nil {
		return nil, err
	}
	return hzMall, nil
}

// MallUpdate - 编辑商城
func (l *MallDao) MallUpdate(mall *ent.HzMall, tx *ent.Tx) error {
	clientDao := l.svcCtx.Orm.HzMall
	if tx != nil {
		clientDao = tx.HzMall
	}
	err := clientDao.UpdateOneID(mall.ID).SetMallSort(mall.MallSort).
		SetMallIcon(mall.MallIcon).
		SetMallName(mall.MallName).
		SetMallURL(mall.MallURL).
		SetMallStatus(mall.MallStatus).
		SetUpdateAt(mall.UpdateAt).
		Exec(l.ctx)
	if err != nil {
		return err
	}
	return nil
}

// MallConditionsPageAll -根据条件分页查询商城图标
func (l *MallDao) MallConditionsPageAll(page, pageSize int64, conditions []predicate.HzMall) ([]*ent.HzMall, int64, error) {
	//计算分页偏移量
	offset := common.Offset(page, pageSize)
	//查询分页数据
	malls, err := l.svcCtx.Orm.HzMall.Query().
		Where(conditions...).
		Offset(int(offset)).
		Limit(int(pageSize)).
		Order(ent.Desc(hzmall.FieldMallSort)).
		All(l.ctx)
	if err != nil {
		return nil, 0, err
	}

	//查询总数
	count, err := l.svcCtx.Orm.HzMall.Query().
		Where(conditions...).
		Count(l.ctx)
	if err != nil {
		return nil, 0, err
	}

	return malls, int64(count), nil
}

// MallConditionsFirst -根据条件查询单个商城图标
func (l *MallDao) MallConditionsFirst(conditions []predicate.HzMall) (*ent.HzMall, error) {
	hzMall, err := l.svcCtx.Orm.HzMall.Query().Where(conditions...).First(l.ctx)
	if err != nil {
		return nil, err
	}
	return hzMall, nil

}
